<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;


class NotLoginController extends Controller
{
    // 下载图片
    public function downloadImg(Request $request)
    {
         //验证表单
        $this->validate($request, [
            'url' => ['required','string'],
            'domain' => ['required','string']
        ]);
        $url = $request->url;
        $domain = $request->domain;
        Log::info('syncImg', ['path'=>"{$domain}{$url}"]);
        $ch = curl_init();//初始化一个cURL会话

        curl_setopt($ch,CURLOPT_URL,"{$domain}{$url}");//抓取url

        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//是否显示头信息
        if(strpos($url,'https://') !== false) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        $data = curl_exec($ch);// 执行一个cURL会话

        $error = curl_error($ch);//返回一条最近一次cURL操作明确的文本的错误信息。
        curl_close($ch);//关闭一个cURL会话并且释放所有资源
        // 创建文件夹
        $filename = public_path().$url;
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir,0777, true);
        }
        $file = fopen($filename,"w+");
        fputs($file,$data);//写入文件
        fclose($file);
        return $error ? false : $filename;
    }

    /**
     * 图片上传(测试)
     * @param Request $request
     * @return array
     */
    public function uploadImg(Request $request)
    {
        if ($request->isMethod('POST')) { //判断文件是否是 POST的方式上传
            $tmp = $request->file('file');
            if ($tmp->isValid()) { //判断文件上传是否有效
                $FileType = $tmp->getClientOriginalExtension(); //获取文件后缀

                $FilePath = $tmp->getRealPath(); //获取文件临时存放位置

                $FileName = date('Y-m-d') . uniqid() . '.' . $FileType; //定义文件名

                Storage::disk()->put($FileName, file_get_contents($FilePath)); //存储文件

                // 发出通知通知其他服务器下载图片

                $this->imgNotice($FileName);
                return $data = [
                    'status' => 0,
                    'path' => $FileName //文件路径
                ];
            }
        }
    }

    // 发送下图片通知
    private function imgNotice($url)
    {
        $domainList = config('domain');
        $curDomain = $_SERVER["HTTP_HOST"];
        foreach ($domainList as $domain) {
            if ($curDomain == $domain) {
                continue;
            }
            Log::info('syncImgPush', ['path'=>'https://'.$curDomain."/uploads/{$url}", 'site'=>"https://{$domain}/admin/notLogin/downloadImg"]);
            $this->curlPost("https://{$domain}/admin/notLogin/downloadImg",["domain" => 'https://'.$curDomain, "url" => "/uploads/{$url}"]);
        }
    }


    private function curlPost($url,$post_data,$header=[])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
